import { build, defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import chalk from 'chalk'
import glob from 'fast-glob'
import ts from '@rollup/plugin-typescript'
import collectionDirInfo from './collectionDirInfo.js'

const args = process.argv.slice(2)[0]
const step = (text, color) => console.log(chalk[color](text))

const run = async () => {
  if (!args) {
    step('未获取到打包目录', 'red')
    return
  }
  step('打包目录: ' + args, 'red')
  const files = await glob(`packages/${args}/**/*.ts`, { onlyFiles: true })

  /* 打包组件配置 */
  const viteCompPackDeploy = (name, entry) => ({
    define: {
      'process.env.NODE_ENV': JSON.stringify('production')
    },
    plugins: [
      react(),
      ts({
        target: 'ESNext',
        rootDir: `packages/${args}/`,
        declaration: true,
        declarationDir: `dist/${args}`,
        exclude: 'node_modules/**',
        allowSyntheticDefaultImports: true
      })
    ],
    build: {
      emptyOutDir: false,
      lib: {
        entry,
        name: name.split('/').slice(-1)[0],
        formats: ['es', 'umd']
      },
      outDir: 'dist',
      cssCodeSplit: false,
      rollupOptions: {
        external: ['react', 'react-dom', 'antd'],
        output: {
          assetFileNames: `${name}/index[extname]`,
          entryFileNames: `${name}/index.[format].js`,
          globals: {
            react: 'react',
            antd: 'antd',
            'react-dom': 'react-dom'
          }
        }
      }
    }
  })

  for (const p of files) {
    const name = p.replace('packages/', '').replace('/index.ts', '')
    /* 打包组件 */
    step('开始打包组件:' + name, 'magenta')
    await build(defineConfig(viteCompPackDeploy(name, p)))
    step('组件打包完成', 'cyan')
  }
  /* 收集目录组件信息 */
  step('开始收集目录信息:' + args, 'magenta')
  await collectionDirInfo(args)
  step('目录收集信息完成', 'cyan')
}

run()
